﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using TerraExplorerX;
using Bussiness;
using Utilities;
using Entity;
using System.Threading;



namespace UI
{
    public partial class MainForm : Form
    {
        private SGWorld61 sgworld;
        private PointSelectForm psf;
        private string currentFlyMode = string.Empty;
        private object currentFlyObj = null;
        private int _FireSource=0;
        //private Form loginForm = null;
        private AlertForm af;
        
        public MainForm()
        {
            EsriUtility.InitEsriLicense();            
            InitializeComponent();
            Initialize();
            sgworld = new SGWorld61();
            //this.loginForm = loginForm;
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            //如果需要处理OnLoadFinished时间，取消下面注释
            sgworld.OnLoadFinished += new _ISGWorld61Events_OnLoadFinishedEventHandler(OnProjectLoadFinished);
            //string flyFile = "http://www.skylineglobe.com/SkylineGlobe/WebClient/PresentationLayer/WebClient/SkyglobeLB.fly";
            string flyFile = @"E:\VirtualCampus\Skyline\FLY6.0\Campus_zhiming.FLY";
            //string flyFile = Application.StartupPath + @"\data\Campus_zhiming.FLY";
            sgworld.Project.Open(flyFile, true, null, null);
        } 
        //1001
        private void OpenWSP_Click(object sender, EventArgs e)
        {
            OpenSceneDialog();           
        }
        //1002
        private void OpenScene_Click(object sender, EventArgs e)
        {
            OpenSceneDialog();   
        }
        //1003
        private void CloseWSP_Click(object sender, EventArgs e)
        {
            sgworld.Project.Close();
        }
        //1004
        private void ExistProgram_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        //110101
        private void Pan_Click(object sender, EventArgs e)
        {
            sgworld.Command.Execute(1049, 0);
        }
        //110102
        private void TrunTile_Click(object sender, EventArgs e)
        {
            sgworld.Command.Execute(1051, 0);
        }
        //110103
        private void ToNorth_Click(object sender, EventArgs e)
        {
            sgworld.Command.Execute(1056, 0);
        }
        //110201
        private void EntireView_Click(object sender, EventArgs e)
        {
            sgworld.Command.Execute(1055, 5);
            SetCurrentFlyObj("cmd",10555);
            
        }
       
        //110202
        private void SceneView_Click(object sender, EventArgs e)
        {
            int itemID = sgworld.ProjectTree.FindItem("知明楼");
            sgworld.Navigate.FlyTo(itemID, ActionCode.AC_FLYTO);
            SetCurrentFlyObj("obj", itemID);
                 
        }
        //110301
        private void StartFly_Click(object sender, EventArgs e)
        {
            if (currentFlyMode!= null)
            {
                if (currentFlyMode.Equals("obj"))
                {
                    sgworld.Navigate.FlyTo(currentFlyObj, ActionCode.AC_FLYTO);
                }
                else
                {
                    int code = Convert.ToInt32(currentFlyObj);
                    int cmdCode = code / 10;
                    int cmdPara = code % 10;
                    sgworld.Command.Execute(cmdCode, cmdPara);
                }
            }

        }
        //110302
        private void Stop_Fly_Click(object sender, EventArgs e)
        {
            sgworld.Navigate.Stop(); 
        }
        //110303
        private void RotateFly_Click(object sender, EventArgs e)
        {
            sgworld.Command.Execute(1057, 0);
            SetCurrentFlyObj("cmd", 10570);
            
        }
        //120101
        private void PointSelect_Click(object sender, EventArgs e)
        {
            //点选查询            
            //PointQueryCommand pq = new PointQueryCommand();
            //int itemID = sgworld.ProjectTree.FindItem("ClassRooms");
            //ILayer61 routeLayer = sgworld.ProjectTree.GetLayer(itemID);
            //int bufferRadius = Int32.Parse(ConfigurationManager.AppSettings["BufferRadius"]);
            //pq.Execute(routeLayer, bufferRadius);
            sgworld.Navigate.FlyTo(sgworld.ProjectTree.FindItem("ClassRooms"));
            sgworld.ProjectTree.SetVisibility(sgworld.ProjectTree.FindItem("知明楼"), false);
            psf.Show();
        }
        //120102
        private void ribbonButton18_Click(object sender, EventArgs e)
        {
            AttributeForm af = new AttributeForm(sgworld);
            sgworld.Navigate.FlyTo(sgworld.ProjectTree.FindItem("ClassRooms"));
            setLayerVisible("知明楼",false);
            setLayerVisible("ClassRooms", false);                  
            af.Show();
        }
        //120103
        private void Btn_OnClass_Click(object sender, EventArgs e)
        {
            setLayerVisible("ClassRooms", false);
            setLayerVisible("知明楼", false);
            //IPopupMessage61 pop = sgworld.Creator.CreatePopupMessage("气泡窗口", "xxxx", 10, 10, 300, 300, 10000);
            //sgworld.Window.ShowPopup(pop);
            GetCurrentCR();
            
        }
        //130101
        private void Select_CR_Click(object sender, EventArgs e)
        {
            int slFireGroupId = AddGroup("着火位置");
            SLHelper helper = new SLHelper();
            DeleteItem(_FireSource.ToString());
            if (Cbox_CRALL.SelectedItem != null)
            {
                string selectedCR = Cbox_CRALL.SelectedItem.Text;
                string imgPath = Application.StartupPath + @"\images\fire.png";

                PropertyQuery pq = new PropertyQuery();
                string[] strs = selectedCR.Split('-');
                int selectedCode = Convert.ToInt32(strs[1]);
                _FireSource = selectedCode;
                EClassRoom crOnFire = pq.Query(selectedCode);
                //标注着火位置               
                helper.AddImgLabel(slFireGroupId,crOnFire, "着火位置", imgPath,true);
                setLayerVisible("知明楼", false);
                setLayerVisible("ClassRooms", false);

            }
           
        }
        //130202
        private void FireDescribe_Click(object sender, EventArgs e)
        {
           

            
        }        
        //130301
        private void Exvacuation_Click(object sender, EventArgs e)
        {
            //this.UseWaitCursor = true;
            this.progressBar1.Value = 1;
            this.MsgLabel.Text = "正在计算疏散路径……";
            if (_FireSource != 0)
            {
                Evacuation ec = new Evacuation(_FireSource, this.progressBar1, this.MsgLabel);
                ec.excute();
                ec.FireSource = _FireSource;
                ec.addFire();
            }
            else
            {
                MessageBox.Show("您还没有标注火灾位置！");
            }
            //this.UseWaitCursor = false;
        }        
        //130302
        private void View_Route_Click(object sender, EventArgs e)
        {
            int slRoutesGroupId=AddGroup("疏散路径组");
            int slTextLabelGroupId = AddGroup("文本标注组");
            Collection<ERouteNode> nodes;
            IPosition61 pos = null;

            SLHelper helper = new SLHelper();
            SysConfigsManager sfm = new SysConfigsManager();
            int lastGroupID = Convert.ToInt32(sfm.GetParaByName("LastGroupID").ToString());
            BestRoutesManager br = new BestRoutesManager();

            if (SessionHelper.CurrentUser.Role != "老师")
            {
                CourseManager cm = new CourseManager();
                IList crCodeList = cm.GetCurrentClassRooms().GetKeyList();                
                
                for (int i = crCodeList.Count - 1, j = 0; i >= 0; i--, j++)
                {
                    int crCode = Convert.ToInt32(crCodeList[i]);
                    nodes = br.BestRouteGetByCode(crCode, lastGroupID);
                    helper.CreatePolyline(nodes, slRoutesGroupId, "知明1-" + crCode, false);
                    pos = sgworld.Creator.CreatePosition(nodes[0].Longitude, nodes[0].Latitude, nodes[0].Altitude);
                    helper.AddTextLabel(slTextLabelGroupId, crCode.ToString(), pos, false);
                }
                sgworld.Navigate.FlyTo(slRoutesGroupId);
            }
            else
            {
                int myCR = Convert.ToInt32(ConfigurationManager.AppSettings["MyClassRoom"]);
                nodes = br.BestRouteGetByCode(myCR, lastGroupID);
                helper.CreatePolyline(nodes, slRoutesGroupId, "知明1-" + myCR, false);                
                pos = sgworld.Creator.CreatePosition(nodes[0].Longitude, nodes[0].Latitude, nodes[0].Altitude);
                helper.AddTextLabel(slTextLabelGroupId, myCR.ToString(), pos, false);
            }
        }
        //130401
        private void CallForHelp_Click(object sender, EventArgs e)
        {
            bool isOk = false;
            FireGroupManager fg = new FireGroupManager();
            isOk=fg.UpdateStatus("1","1");
            if (isOk == true)
            {
                MessageBox.Show("已经成功发出救援！");
            }
        }
        //130501
        private void RunAlongRouad_Click(object sender, EventArgs e)
        {
            int myClassRoom = Convert.ToInt32(ConfigurationManager.AppSettings["MyClassRoom"]);
            CourseManager cm = new CourseManager();
            IList crList = cm.GetCurrentClassRooms().GetKeyList();
            if (crList.Contains(myClassRoom))
            {
                RunByRoute(myClassRoom);
            }
            else
            {
                MessageBox.Show("该教室当前没有安排课程！");
            }
        }
        //130502
        private void ViewHistory_Click(object sender, EventArgs e)
        {
            RouteHistoryForm rhf = new RouteHistoryForm();
            rhf.Show();
        }
        //130601
        private void Btn_Report_Click(object sender, EventArgs e)
        {
            if (_FireSource != 0)
            {
                ReportForm rp = new ReportForm(_FireSource);
                rp.Show();
            }
            else
            {
                FireGroupManager fg = new FireGroupManager();
                int source = fg.GetLastFireSource();
                ReportForm rp = new ReportForm(source);
                rp.Show();
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (SessionHelper.CurrentUser.Role == "老师")
            {  
                BestRoutesManager br = new BestRoutesManager();
                int myCR = Convert.ToInt32(ConfigurationManager.AppSettings["MyClassRoom"]);
                Collection<ERouteNode> nodes = br.BestRouteGetByCodeAndStatus(myCR);
                if (nodes.Count > 0&&af.DiaLogShowed==false)
                {
                    af.DiaLogShowed = true;
                    af.ShowDialog();                    
                }
            }
            else if (SessionHelper.CurrentUser.Role == "消防队")
            {
                FireGroupManager fg = new FireGroupManager();
                bool hasNew = fg.HasNewCall(3);
                if (hasNew && af.DiaLogShowed == false)
                {
                    af.DiaLogShowed = true;
                    fg.UpdateStatus(null, "2");
                    af.ShowDialog();  
                }
            }
            else if (SessionHelper.CurrentUser.Role == "医护人员")
            {
                FireGroupManager fg = new FireGroupManager();
                bool hasNew = fg.HasNewCall(4);
                if (hasNew && af.DiaLogShowed == false)
                {
                    af.DiaLogShowed = true;
                    fg.UpdateStatus("2", null);
                    af.ShowDialog();
                }
            }
        }
        //140101
        private void FireChuckRoute_Click(object sender, EventArgs e)
        {
            Collection<ERouteNode> nodes = new Collection<ERouteNode>();
            FireGroupManager fg = new FireGroupManager();
            CampusNALayer cl = new CampusNALayer();
            SLHelper helper = new SLHelper();
            string modelUrl = Application.StartupPath + @"\vehicle\fire\FireChunk.xpl2";

            if (_FireSource != 0)
            {
                nodes = cl.SolveRoute(_FireSource);
                
            }
            else
            {                
                int source = fg.GetLastFireSource();
                nodes = cl.SolveRoute(source);
            }
            helper._Speed = 30;
            helper._ModelScale = 0.1;
            helper._ModelURL = modelUrl;            
            helper.RunByNodeCollection(nodes);
            int itemID = helper.AddGroup("消防车路径组");
            helper.CreatePolyline(nodes, itemID, "消防车疏散路径", false);
            //EFacility pump = cl.ClosestPump;            
            fg.UpdateStatus(null, "3");  
        }
        //140102
        private void Ambulance_Click(object sender, EventArgs e)
        {
            Collection<ERouteNode> nodes = new Collection<ERouteNode>();
            FireGroupManager fg = new FireGroupManager();
            CampusNALayer cl = new CampusNALayer();
            SLHelper helper = new SLHelper();
            string modelUrl = Application.StartupPath + @"\vehicle\fire\FireChunk.xpl2";
                       
            nodes = cl.SolveHospitalRoute();

            helper._Speed = 30;
            helper._ModelScale = 0.1;
            helper._ModelURL = modelUrl;    
            helper.RunByNodeCollection(nodes);
            int itemID = helper.AddGroup("消防车路径组");
            helper.CreatePolyline(nodes, itemID, "消防车疏散路径", false);
            fg.UpdateStatus("3", null);     
        }
        //150101
        private void UserLogin_Click(object sender, EventArgs e)
        {
            //this.loginForm.Visible = true;
            LoginForm lf = new LoginForm();
            lf.ShowDialog();
            if (lf.DialogResult == DialogResult.OK)
            {
                string userName = lf.UserName;
                string psw = lf.Psw;
                if (userName != string.Empty && psw != string.Empty)
                {
                    bool isSucceed = login(userName, psw);
                    if (isSucceed)
                    {
                        getAuthority();
                        SetTitle();
                    }
                    else
                    {
                        MessageBox.Show("用户名或密码不正确！");
                    }
                }
            }
        }
        //150102
        private void LogOut_Click(object sender, EventArgs e)
        {
            logOut();
        }
        //160101
        private void Btn_Setting_Click(object sender, EventArgs e)
        {
            SysSettingForm ss = new SysSettingForm();
            ss.Show();
        }


        ////***************************Pravite Method Below************************////
        ////***************************Pravite Method Below************************////
        private void OpenSceneDialog()
        {
            OpenFileDialog openSceneFileDialog = new OpenFileDialog();
            openSceneFileDialog.InitialDirectory = System.Windows.Forms.Application.StartupPath + @"\data\chap8";
            openSceneFileDialog.Filter = "Fly数据(*.FLY)|*.FLY";
            openSceneFileDialog.RestoreDirectory = true;
            if (openSceneFileDialog.ShowDialog() == DialogResult.OK)
            {
                string SceneFilePath = openSceneFileDialog.FileName.Substring(0, openSceneFileDialog.FileName.Length - openSceneFileDialog.SafeFileName.Length);
                string SceneFileName = openSceneFileDialog.SafeFileName;

                //Open3dFile(SceneFilePath + SceneFileName);
                sgworld.Project.Open(SceneFileName, true, null, null);
            }
        }
        //场景加载完成
        void OnProjectLoadFinished()
        {
            int itemID = sgworld.ProjectTree.FindItem("WalkWay");
            sgworld.Navigate.FlyTo(itemID, ActionCode.AC_FLYTO);
            InstantObject();            
        }
              
        
        private void SetCurrentFlyObj(string mode,object o)
        {
            this.currentFlyMode=mode;
            this.currentFlyObj=o;
        }
        private void GetCurrentCR()
        {
            int slOnClassGroupId=AddGroup("当前上课教室组");
            CourseManager cm = new CourseManager();
            PropertyQuery pq = new PropertyQuery();
            SLHelper helper = new SLHelper();
            SortedList croomList = cm.GetCurrentClassRooms();
            IList keyList = croomList.GetKeyList();
            IList valueList = croomList.GetValueList();
            for (int i = 0; i < croomList.Count; i++)
            {
                int crCode = Convert.ToInt32(keyList[i]);
                EClassRoom cr = pq.Query(crCode);
                string imgPath = Application.StartupPath + @"\images\class.png";
                string str = "知明1-" + cr.CRCode.ToString() + "  上课人数：" + valueList[i] + "人";
                helper.AddImgLabel(slOnClassGroupId,cr, str, imgPath, false);
            }

        }       
        private void setLayerVisible(string layerName,bool isVisible)
        {
            sgworld.ProjectTree.SetVisibility(sgworld.ProjectTree.FindItem(layerName), isVisible); 
        }
        private void DeleteItem(string Name)
        {
            int itemID = -1;
            itemID=sgworld.ProjectTree.FindItem(Name);
            if (itemID != -1)
            {
                sgworld.ProjectTree.DeleteItem(itemID);
            }
        }
        private void RunByRoute(int crCode)
        {
            SysConfigsManager cfm = new SysConfigsManager();
            Collection<ERouteNode> nodes = new Collection<ERouteNode>();
            BestRoutesManager br = new BestRoutesManager();

            int lastGID = Convert.ToInt32(cfm.GetParaByName("LastGroupID").ToString());
            nodes = br.BestRouteGetByCode(crCode,lastGID);

            string modelUrl = Application.StartupPath + @"\vehicle\man.xpc";
            SLHelper helper = new SLHelper();
            helper._ModelURL = modelUrl;
            helper._Speed = 3;
            helper._ActionCode = ActionCode.AC_FOLLOWCOCKPIT;
            helper.RunByNodeCollection(nodes);
            
        }
        private void InstantObject()
        {
            psf = new PointSelectForm(sgworld);            
        }
        private void Initialize()
        {
            InitializeCbox_CRALL();
            //login("niming","123456");
            logOut();
            getAuthority();
            SetTitle();
            af = new AlertForm(); 
        }
        private void InitializeCbox_CRALL()
        {
            PropertyQuery pq = new PropertyQuery();
            List<int> crCodes = pq.QueryAllCR();
            crCodes.Sort();
            for (int i = 0; i < crCodes.Count; i++)
            {
                RibbonButton rb = new RibbonButton();
                rb.Text = "知明1-" + crCodes[i].ToString();
                this.Cbox_CRALL.DropDownItems.Add(rb);
            } 
        }
        private int AddGroup(string name)
        {           
            DeleteItem(name);
            sgworld.ProjectTree.CreateGroup(name, 0);
            int itemID = sgworld.ProjectTree.FindItem(name);
            return itemID;
        }    
       
        private bool login(string userName, string psw)
        {
            bool isSucceed = false;
            AccountManager am = new AccountManager();
            EAccount account = am.login(userName, psw);
            if (account != null)
            {
                SessionHelper.CurrentUser.UserName = account.UserName;
                SessionHelper.CurrentUser.Role = account.RoleName;
                SessionHelper.CurrentUser.Authorities = account.GetAuthorities();
                isSucceed = true;
            }
            return isSucceed;
        }
        private void logOut()
        {
            SessionHelper.CurrentUser.UserName = null;
            SessionHelper.CurrentUser.Role = null;
            SessionHelper.CurrentUser.Authorities = null;
            //Application.Exit();
            login("admin","123456");
            getAuthority();
            SetTitle();
            login("niming","123456");
            getAuthority();
            SetTitle();
        }
        private void getAuthority()
        {            
            IList authorities = SessionHelper.CurrentUser.Authorities;
            for (int i = 0; i < ribbon1.Tabs.Count; i++)
            {
                int panelCount = ribbon1.Tabs[i].Panels.Count;
                int realPanelCount = 0;
                for (int j = 0; j < ribbon1.Tabs[i].Panels.Count; j++)
                {
                    int btnCount = ribbon1.Tabs[i].Panels[j].Items.Count;
                    int realCount = 0;
                    for (int k = 0; k < ribbon1.Tabs[i].Panels[j].Items.Count; k++)
                    {
                        int ii = i + 1;
                        int jj = j + 1;
                        int kk = k + 1;
                        string code = "1" + ii + "0" + jj + "0" + kk;
                        //if not contains,set visibile equals false                        
                        if (!authorities.Contains(code))
                        {
                            ribbon1.Tabs[i].Panels[j].Items[k].Visible = false;
                            realCount++;
                        }
                        else
                        {
                            ribbon1.Tabs[i].Panels[j].Items[k].Visible = true;
                        }
                    }
                    if (btnCount == realCount)
                    {
                        //关闭panel
                        ribbon1.Tabs[i].Panels[j].Visible = false;
                        realPanelCount++;
                    }
                    else
                    {
                        ribbon1.Tabs[i].Panels[j].Visible = true;
                    }
                }
                if (panelCount == realPanelCount)
                {
                    //关闭菜单
                    ribbon1.Tabs[i].Visible = false;
                }
                else
                {
                    ribbon1.Tabs[i].Visible = true;
                }
            }
        }
        private void SetTitle()
        {
            this.Text = "三维校园楼宇突发事件应急响应系统("+SessionHelper.CurrentUser.Role+")";
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

       
       
    }
   
}
